define([ './module' ], function(ordermodule) {
	'use strict';

	ordermodule.controller('order',['$scope','$http','$location','Upload','$timeout','GoodsTypeService','goodscategoryService',function($scope,$http,$location,Upload,$timeout,GoodsTypeService,goodscategoryService){
		
		//查询所有商品类型
		$scope.findallgoodstype=function(){
			var promise=GoodsTypeService.query();
			promise.then(function(data){
				$scope.goodstypeselect=data.beanlists;
			},function(data){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		};

		
		//获取所有一级商品分类
		$scope.findNavAll=function(){
			var promise=goodscategoryService.query();
			promise.then(function(data){
				$scope.navselect=data.beanlists;
			},function(data){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		};
		//获取所有二级商品分类
		$scope.navchange=function(){
			if($scope.selectednav!=undefined){
				$http({
					method:'POST',
					url:'../mall/goods/goodscategory/findCategoryAllByParentId.action',
					data:{
						'id':$scope.selectednav.id
					}
				}).success(function(data,status,headers,config){
					if(data.sucflag&&data.beanlists.length>0){
						$scope.errors={};
						$scope.ltypeselect=[];
						$scope.ltypeselect=angular.fromJson(data.beanlists);
						$scope.ltypecategoryshow=true;
					}else{
						$scope.ltypecategoryshow=false;
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});

			};
		};
		//获取所有三级商品分类
		$scope.ltypechange=function(){
			if($scope.selectedltype!=undefined){
				$http({
					method:'POST',
					url:'../mall/goods/goodscategory/findCategoryAllByParentId.action',
					data:{
						'id':$scope.selectedltype.id
					}
				}).success(function(data,status,headers,config){
					if(data.sucflag&&data.beanlists.length>0){
						$scope.errors={};
						$scope.stypeselect=[];
						$scope.stypeselect=angular.fromJson(data.beanlists);
						$scope.stypeidcategoryshow=true;
					}else{
						$scope.stypeidcategoryshow=false;
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});

			};
		};

		//过滤搜索需要的货物
		$scope.filterSearchProduct=function(){
			if($scope.selectedgoodstype==undefined){
				$scope.errors={
						show:true,
						msg:'请选择商品类型'
				}
				return false;
			}
			var psn=""
			if($scope.psn!=undefined){
				psn=$scope.psn;
			}
			var navid="";
			var ltypeid="";
			var stypeid="";
			if($scope.selectednav!=undefined){
				navid=$scope.selectednav.id
			}
			if($scope.selectedltype!=undefined){
				ltypeid=$scope.selectedltype.id;
			}
			if($scope.selectedstype!=undefined){
				stypeid=$scope.selectedstype.id;
			}
			$http({
				method:'POST',
				url:'../mall/products/filtersearch.action',
				data:{
					'goodstypeid':$scope.selectedgoodstype.goodstypeid,
					'psn':psn,
					'navid':navid,
					'ltypeid':ltypeid,
					'stypeid':stypeid
				}
			}).success(function(data,status,headers,config){
				if(data.sucflag&&data.beanlists.length>0){
					$scope.errors={};
					$scope.basepath=data.basepath;
					$scope.searchresult=data.beanlists;

				}
			}).
			error(function(data,status,headers,config){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		};
		//选定货物
		var sp=[];
		$scope.pushToSelectedProducts=function(index,product){
			sp.push(product);
			$scope.selectedproducts=sp;
			$scope.shouldpay=0.0;
			//修改最高价格和最低价格
			angular.forEach($scope.selectedproducts,function(d,i,a){
					$scope.shouldpay+=d.memberprice;
			});
		};
		
		$scope.removeSelectedProducts=function(index){
			$scope.selectedproducts.splice(index,1);
			$scope.shouldpay=0.0;

			angular.forEach($scope.selectedproducts,function(d,i,a){
				$scope.shouldpay+=d.memberprice;
			});
		}

		
		
		/**
		 * 搜索会员的收获地址信息和开票信息
		 */
		$scope.filterSearchMemberDeliveraddressAndInvoice=function(){
			if($scope.loginname==undefined){
				$scope.errors={
						show:true,
						msg:'请输入会员账号活着手机号进行搜索'
				}
				return false;
			}
			
			$http({
				method:'POST',
				url:'../mall/order/filterMemberDeliverAddressAndInvoice.action',
				data:{
					'loginname':$scope.loginname
				}
			}).success(function(data,status,headers,config){
				if(data.sucflag){
					$scope.errors={};
					$scope.memberdeliveraddresssearchresult=data.mDeliverAddressTsList;
					$scope.memberinvoicesearchresult=data.memberinvoList;
				}
			}).
			error(function(data,status,headers,config){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		}
		//选定的收获地址
		
		$scope.pushToSelectedMemberDeliveraddress=function(index,md){
			var mda=[];
			mda.push(md);
			$scope.selectedmda=mda;
		};
		
		$scope.removeSelectedMemberDeliveraddress=function(index){
			$scope.selectedmda.splice(index,1);
		}

		//选定发票信息
		
		$scope.pushToSelectedMemberInvoice=function(index,m){
			var mi=[];
			mi.push(m);
			$scope.selectedmi=mi;
		};
		
		$scope.removeSelectedMemberInvoice=function(index){
			$scope.selectedmi.splice(index,1);
		}

		
		/**
		 * 搜索会员的收获地址信息和开票信息
		 */
		$scope.filterLogisticsBusiness=function(){
			$http({
				method:'POST',
				url:'../mall/order/filterLogisticsBusiness.action'
			}).success(function(data,status,headers,config){
				if(data.sucflag){
					$scope.errors={};
					$scope.logisticslists=data.logisticsBusinessTs;
				}
			}).
			error(function(data,status,headers,config){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		}
		
		/**
		 * 搜索支付方式
		 */
		$scope.filterPayment=function(){
			$http({
				method:'POST',
				url:'../mall/order/filterPayment.action'
			}).success(function(data,status,headers,config){
				if(data.sucflag){
					$scope.errors={};
					$scope.paymentlist=data.mPaymentMs;
				}
			}).
			error(function(data,status,headers,config){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		}
		
		
		

		//通过location中的operate参数区分操作行为
		var operate=$location.search().operate;
		if(operate!=undefined&&operate=="save"){
			//控制保存按钮显示
			$scope.savebtn={show:true};
			//默认servicecode
			$scope.servicecode="code";
			$scope.title='添加订单';
			
			$scope.save=function(){
				

				var selectOrderProducts="";
				if($scope.selectedproducts==undefined){
					$scope.errors={
							show:true,
							msg:'请选择订单货物'
					}
					return false;
				}else{
					var temparray=[];
					angular.forEach($scope.selectedproducts,function(d,i,a){
							temparray.push(d.productid);
					});
					selectOrderProducts=temparray.join(",");
				}
				if($scope.loginname==undefined){
					$scope.errors={
							show:true,
							msg:'请输入会员账号或者手机号'
					}
					return false;
				}

				var addressid="";
				if($scope.selectedmda==undefined){
					$scope.errors={
							show:true,
							msg:'请选择订单收获地址'
					}
					return false;
				}else{
					angular.forEach($scope.selectedmda,function(d,i,a){
						addressid=d.id;
					});
				}
				
				var memberinvoiceid="";
				if($scope.selectedmi==undefined){
					$scope.errors={
							show:true,
							msg:'请选择订单发票'
					}
					return false;
				}else{
					angular.forEach($scope.selectedmda,function(d,i,a){
						memberinvoiceid=d.id;
					});
				}
				
				if($scope.logisticsid==undefined){
					$scope.errors={
							show:true,
							msg:'请选择物流商'
					}
					return false;
				}
				
				if($scope.paymentid==undefined){
					$scope.errors={
							show:true,
							msg:'请选择支付方式'
					}
					return false;
				}
				
				if($scope.freight==undefined){
					$scope.errors={
							show:true,
							msg:'请输入订单运费'
					}
					return false;
				}
				if($scope.shouldpay==undefined){
					$scope.errors={
							show:true,
							msg:'请输入订单总价'
					}
					return false;
				}
				
				$http({
					method:'POST',
					url:'../mall/order/save.action',
					data:{
						"selectOrderProducts":selectOrderProducts,
						"loginname":$scope.loginname,
						"addressid":addressid,
						"memberinvoiceid":memberinvoiceid,
						"logisticsid":$scope.logisticsid,
						"paymentid":$scope.paymentid,
						"freight":$scope.freight,
						"shouldpay":$scope.shouldpay
					}
				})
				.success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.errors={};
						$scope.info={
								show:true,
								msg:'订单添加成功'
						}
						$location.path('/orderment');
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});

			}
		}

		if(operate=='edit'){
			
			var id=$location.search().id;
			alert(id);
			if(id!=undefined&&id!=""){
				$http({
					method:'POST',
					url:'../mall/goods/find.action',
					data:{
						'id':id
					}
				}).success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.title='正在对商品--'+data.bean.goodsname+'--进行编辑';
						$scope.isoutsite=data.bean.isoutsite;
						if($scope.isoutsite=="1"){
							//站内商品
							$scope.outsiteshow=true;
							$scope.outsitelinkshow=false;
							//填充选择的货物
							$scope.selectedproducts=data.pbeanlists;


						}else{
							//站外商品
							$scope.outsiteshow=false;
							$scope.outsitelinkshow=true;
							$scope.outsitelink=data.bean.outsitelink;
						}
						//显示选择的商品类型
						$scope.lastgoodstypenameshow=true;
						$scope.lastgoodstypename=data.bean.goodstypename;
						$scope.goodstypeid=data.bean.goodstypeid;
						$scope.modifygoodstypeshow=true;
						$scope.goodstypeshow=false;
						//显示选择的商品品牌
						$scope.lastbrandnameshow=true;
						$scope.brandid=data.bean.brandid;
						$scope.lastbrandname=data.bean.brandname;
						$scope.modifybrandnameshow=true;
						$scope.brandnameshow=false;
						$scope.goodsattrs=angular.fromJson(data.bean.pattrs);
						//显示分类
						$scope.lastcategoryshow=true;
						$scope.lastcategory=data.bean.nname+"-"+data.bean.lname+"-"+data.bean.sname;
						$scope.navid=data.bean.navid;
						$scope.nname=data.bean.nname;
						$scope.ltypeid=data.bean.ltypeid;
						$scope.lname=data.bean.lname;
						$scope.stypeid=data.bean.stypeid;
						$scope.sname=data.bean.sname;
						//显示分类修改
						$scope.modifycategoryshow=true;
						$scope.goodsname=data.bean.goodsname;
						$scope.subgoodsname=data.bean.subgoodsname;
						$scope.minprice=data.bean.minprice;
						$scope.maxprice=data.bean.maxprice;
						$scope.allvsales=data.bean.allvsales;
						$scope.allsales=data.bean.allsales;
						$scope.alltotalcomment=data.bean.alltotalcomment;
						$scope.alltotalzan=data.bean.alltotalzan;
						$scope.metakey=data.bean.metakey;
						$scope.metades=data.bean.metades;
						$scope.msync=data.bean.msync;
						$scope.sort=data.bean.sort;
						$scope.status=data.bean.status;
						$scope.commoditylist=data.bean.commoditylist;
						$scope.detail=data.gdbean.detail;
						$scope.allrmainfiles.push(data.ifb);
						angular.forEach(data.ifbs,function(d,i,a){
								$scope.allrfiles.push(d);
						});
						$scope.servicecode=data.bean.servicecode;
						$scope.updatebtn={show:true};
					}
				}).error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}

			//点击修改商品类型按钮
			$scope.clickmodifygoodstype=function(){
				$scope.goodstypeshow=true;
			}
			//点击修改品牌
			$scope.clickmodifybrandname=function(){
				$scope.brandnameshow=true;
			}
			//点击修改分类
			$scope.clickmodifycategory=function(){
				$scope.navcategoryshow=true;
			}

			$scope.update=function(){
				var outsitelink="";
				if($scope.isoutsite=="0"){
					outsitelink=$scope.outsitelink;
				}
				var productids="";
				if($scope.selectedproducts==undefined&&$scope.isoutsite=="1"){
					$scope.errors={
							show:true,
							msg:'请选择货物'
					}
					return false;
				}else{
					var temparray=[];
					angular.forEach($scope.selectedproducts,function(d,i,a){
							temparray.push(d.productid);
					});
					productids=temparray.join(",");
				}

				var goodstypeid="";
				var goodstypename="";
				if($scope.goodstypeshow){
					if($scope.selectedgoodstype==undefined){
						$scope.errors={
								show:true,
								msg:'请选择商品类型'
						}
						return false;
					}else{
						goodstypeid=$scope.selectedgoodstype.goodstypeid;
						goodstypename=$scope.selectedgoodstype.name;
					}
				}else{
					goodstypeid=$scope.goodstypeid;
					goodstypename=$scope.lastgoodstypename;
				}
				var brandid="";
				var brandname="";
				if($scope.brandnameshow){
					if($scope.selectedbrands==undefined){
						$scope.errors={
								show:true,
								msg:'请选择品牌'
						}
						return false;
					}else{
						brandid=$scope.selectedbrands.brandid;
						brandname=$scope.selectedbrands.brandname;
					}
				}else{
					brandid=$scope.brandid;
					brandname=$scope.lastbrandname;
				}
				if($scope.navcategoryshow){
					var navid="";
					var nname="";
					if($scope.selectednav==undefined){
						$scope.errors={
								show:true,
								msg:'请选择一级分类'
						}
						return false;
					}else{
						navid=$scope.navid;
						nname=$scope.nname;
					}
					var ltypeid="";
					var lname="";
					if($scope.selectedltype!=undefined){
							ltypeid=$scope.selectedltype.id;
							lname=$scope.selectedltype.name;
					}else{
						ltypeid=$scope.ltypeid;
						lname=$scope.lname;
					}

					var stypeid="";
					var sname="";
					if($scope.selectedstype!=undefined){
						stypeid=$scope.selectedltype.id;
						sname=$scope.selectedltype.name;
					}else{
						stypeid=$scope.stypeid;
						sname=$scope.sname;
					}
				}else{
					var navid=$scope.navid;
					var nname=$scope.nname;
					var ltypeid=$scope.ltypeid;
					var lname=$scope.lname;
					var stypeid=$scope.stypeid;
					var sname=$scope.sname;
				}

				if($scope.goodsname==undefined){
					$scope.errors={
							show:true,
							msg:'请输入商品标题'
					}
					return false;
				}
				if($scope.subgoodsname==undefined){
					$scope.errors={
							show:true,
							msg:'请输入商品副标题'
					}
					return false;
				}
				if($scope.sort==undefined){
					$scope.errors={
							show:true,
							msg:'请输入商品排序'
					}
					return false;
				}
				if($scope.commoditylist==undefined){
					$scope.errors={
							show:true,
							msg:'请输入商品清单'
					}
					return false;
				}
				if($scope.detail==undefined){
					$scope.errors={
							show:true,
							msg:'请输入商品介绍'
					}
					return false;
				}
				if($scope.allrmainfiles.length==0){
					$scope.errors={
							show:true,
							msg:'请上传主图'
					}
					return false;
				}
				if($scope.allrfiles.length==0){
					$scope.errors={
							show:true,
							msg:'请上传主图'
					}
					return false;
				}
				
				$http({
					method:'POST',
					url:'../mall/goods/update.action',
					data:{
						"allvsales":$scope.allvsales,
						"allsales":$scope.allsales,
						"alltotalcomment":$scope.alltotalcomment,
						"alltotalzan":$scope.alltotalzan,
						"servicecode":$scope.servicecode,
						"isoutsite":$scope.isoutsite,
						"outsitelink":outsitelink,
						"productids":productids,
						"goodstypeid":goodstypeid,
						"goodstypename":goodstypename,
						"brandid":brandid,
						"brandname":brandname,
						"pattrs":angular.toJson($scope.goodsattrs),
						"navid":navid,
						"nname":nname,
						"ltypeid":ltypeid,
						"lname":lname,
						"stypeid":stypeid,
						"sname":sname,
						"goodsname":$scope.goodsname,
						"subgoodsname":$scope.subgoodsname,
						"minprice":$scope.minprice,
						"maxprice":$scope.maxprice,
						"metakey":$scope.metakey,
						"metades":$scope.metades,
						"commoditylist":$scope.commoditylist,
						"mainimg":angular.toJson($scope.allrmainfiles),
						"imgs":angular.toJson($scope.allrfiles),
						"detail":$scope.detail,
						"msync":$scope.msync,
						"sort":$scope.sort,
						"status":$scope.status,
						"id":id
					}
				})
				.success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.errors={};
						$scope.info={
								show:true,
								msg:'商品更新成功'
						}
						$location.path('/goodsment');
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});

			}
			//点击修改菜系
			$scope.clickmodifyfoodtype=function(){
				$scope.foodtypeshow=true;
			}
		}





	}]);

	ordermodule.controller('orderment',ServerGoodsmentCtrl);
	//查询列表数据
	function ServerGoodsmentCtrl($http,$location,$compile,$scope,$rootScope,$resource,DTOptionsBuilder,DTColumnBuilder,DTAjaxRenderer){
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
		vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
			type:'POST',
			url:'../mall/goods/findByPage.action',
			dataSrc:'data'
		})
		.withOption('processing',true)
		.withOption('paging',true)
		.withOption('serverSide',true)
		.withOption('createdRow',function(row,data,dataIndex){
			$compile(angular.element(row).contents())($scope);
		})
		.withOption('headerCallback', function(header) {
            if (!$scope.headerCompiled) {
                $scope.headerCompiled = true;
                $compile(angular.element(header).contents())($scope);
            }
        })
        .withOption('stateSave', true)
        .withOption('rowCallback',rowCallback)
		.withPaginationType('full_numbers')
		.withLanguageSource('./app/language/chinese.json')

		$scope.$on('handleRequest',function(){

		});
		vm.dtColumns=[
		              DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
		            	  vm.selected[full.id]=false;
		            	  return "<input type='checkbox' ng-model=\"showCase.selected['"+data.id+"']\" ng-click=\"showCase.toggleOne(showCase.selected)\">";
		              }),
		              DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
		              DTColumnBuilder.newColumn(null).withTitle('图片').notSortable().renderWith(imgHtml),
				         
			          DTColumnBuilder.newColumn('goodsname').withTitle('商品标题').notSortable(),
			          DTColumnBuilder.newColumn('subgoodsname').withTitle('副标题').notSortable(),
			          DTColumnBuilder.newColumn('nname').withTitle('分类').notSortable(),
			          DTColumnBuilder.newColumn('goodstypename').withTitle('商品类型').notSortable(),
			          DTColumnBuilder.newColumn('price').withTitle('价格').notSortable(),
			        	DTColumnBuilder.newColumn('msync').withTitle('移动端状态').notSortable(),
			          DTColumnBuilder.newColumn('sort').withTitle('排序').notSortable(),
			          DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
			          DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable(),
			          DTColumnBuilder.newColumn('version').withTitle('版本号').notSortable(),
			          DTColumnBuilder.newColumn(null).withTitle('操作').notSortable().renderWith(actionHtml)];
		function imgHtml(data,type,full,meta){
			return '<img style="width:50px;height:50px;" ng-src="'+data.smainimg+'" alt="Photo" />';
		}
		function actionHtml(data,type,full,meta){
			return "<button  ng-click=\"edit('"+data.id+"')\" class='btn btn-warning'><i class='fa fa-edit'></i></button>";
		}

		function reloadData(){
			var resetPaging = false;
	        vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}


		//表格中编辑按钮
		$scope.edit=function(id,name){
			$location.path('/goods').search({'operate':'edit','id':id});
		}
		
		

		/**
		 * 跳转到添加商品类型和参数页面
		 */
		$scope.save=function(){
			$location.path('/goods').search({'operate':'save'});
		}

		$scope.del=function(){
			var i=0;
			var ids=[];
			angular.forEach(vm.selected, function(data,index,array){
				if(data){
					i++;
					ids.push(index);
				}
			});
			if(i==0){
				$scope.errors={
						show:true,
						msg:'请选择一条记录'
				}
			}else{
				$scope.errors={
						show:false
				}
				//批量删除数据
				var idstrs=ids.join(",");
				$http({
					method:'POST',
					url:'../mall/goods/del.action',
					data:{
						'ids':idstrs
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.errors={};
						$scope.info={
								show:true,
								msg:'删除成功'
						}
						reloadData();
					}

				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;
		}

		function someClickHandler(info) {
	        vm.message = info.id + ' - ' + info.name;
	    }
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
	        $('td', nRow).bind('click', function() {
	            $scope.$apply(function() {
	                vm.someClickHandler(aData);
	            });
	        });
	        return nRow;
		}

	}
});
